package com.heima.search.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.SearchArticleVo;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.pojos.EsArticle;
import com.heima.search.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 基本搜索业务
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
       //TODO
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("app_info_article");
            // 2.准备DSL
            // 2.1.query
            String key = dto.getSearchWords();
            if (key == null || "".equals(key)) {
                request.source().query(QueryBuilders.matchAllQuery());
            } else {
                request.source().query(QueryBuilders.matchQuery("all", key));
            }

            // 2.2.分页
            int page = dto.getPageNum();
            int size = dto.getPageSize();
            if (page<=0){
                page=1;
            }
            request.source().from((page - 1) * size).size(size);

            // 3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
           // List list = handleResponse(response);
            List<EsArticle> esArticles = handleResponse(response);
            List<SearchArticleVo> searchArticleVoList=new ArrayList<>();
            esArticles.forEach(x->{//SearchArticleVo
                SearchArticleVo searchArticleVo = BeanUtil.copyProperties(x, SearchArticleVo.class);
                searchArticleVoList.add(searchArticleVo);
            });
            return ResponseResult.okResult(searchArticleVoList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    // 结果解析
    private List<EsArticle> handleResponse(SearchResponse response) {
        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
       // long total = searchHits.getTotalHits().value;
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<EsArticle> esArticles = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            EsArticle esArticle = JSON.parseObject(json, EsArticle.class);
            // 放入集合
            esArticles.add(esArticle);
        }
        // 4.4.封装返回
       // return new PageResult(total, esArticles);
        return esArticles;
    }


    /**
     * 自动补全功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(UserSearchDto dto) {
       //TODO
        return null;
    }
}
